package no.uia.IKT508.XH;

import no.uia.IKT05.XH.R;
import no.uia.IKT508.XH.XHTalkDialog.ChatListener;
import no.uia.IKT508.XH.XHVariable.State;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;



public class XHChat extends Activity {
	
	private static final String TAG = "no.uia.IKT508.XH.Chat";
	
	//the screen components
	private Menu menu;
	
	private Button advertButton;
	private Button discoveryButton;
	public Button disconnectButton;
	public Button talkButton;
	private TextView mTextV;
	private EditText nameEdit;
	
	//the disconnect and audio button are invisible in the beginning
	private int mVisibility = View.INVISIBLE;
	
	private String name;
	
	//each application contains one client and server
	public static XHClient mClient;
	public static XHService mService;
	
	//the state of current client
	private State state_C;
	
	//the state of current service
	private State state_S;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	Log.i(TAG, "onCreate()");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        advertButton = (Button)findViewById(R.id.AdvertisementButton);
        //when click on the advertisement button, start advertising the well name
        advertButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				name = nameEdit.getText().toString();
				if (name.length() == 0)
				{
					//the input should not be empty
					Toast.makeText(getApplicationContext(), "Please input the name firstly!", Toast.LENGTH_LONG).show();
				}
				else
				{
					//start advertising
					mService.startAdvertisement(name);
				}
			}
		});
        
        nameEdit = (EditText)findViewById(R.id.NameEdit);
        
        discoveryButton = (Button)findViewById(R.id.DiscoveryButton);
        //when click on the discovery button, start discovering the well name
        discoveryButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				name = nameEdit.getText().toString();
				if (name.length() == 0)
				{
					//the input should not be empty
					Toast.makeText(getApplicationContext(), "Please input the name firstly!", Toast.LENGTH_LONG).show();
				}
				else
				{
				
					//pass the well_name to the client to avoid the client join the session created by the local service
					mClient.setWellName(XHVariable.NAME_PREFIX + "." + name);
					mClient.startDiscover();
				}
				
			}
		});
        
        disconnectButton = (Button)findViewById(R.id.DisconnectButton);
        disconnectButton.setVisibility(mVisibility);
        //disconnect the connection
        disconnectButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mClient.startDisconnect();
				mService.startDisconeect();
				mVisibility = View.INVISIBLE;
				disconnectButton.setVisibility(mVisibility);
				talkButton.setVisibility(mVisibility);
				
			}
		});
        
        talkButton = (Button)findViewById(R.id.startTalkButton);
        talkButton.setVisibility(mVisibility);
        talkButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivityForResult(new Intent(getApplicationContext(), XHTalkDialog.class), 0);
				
			}
		});
        
        //show the state
        mTextV = (TextView)findViewById(R.id.StateView);
        mTextV.setText("State: Idle!");
        
        //create the client and service, 
        //passing the activity to them to launch the talk activity
        mClient = new XHClient(mClientListener);
        mService = new XHService(mServiceListener);
        
    }
    
    //this listener is to launch the relative codes once the connection is finished
	//you can call this listener is the router part
    private XHListener mClientListener = new XHListener()
    {
		@Override
		public void OnComplete(Object value, int size) {
			state_C = State.CONNECTED_C;
			//if the local service has been connected, launch the talk dialog
			if (State.CONNECTED_S == state_S)
			{
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						mVisibility = View.VISIBLE;
						disconnectButton.setVisibility(View.VISIBLE);
						talkButton.setVisibility(View.VISIBLE);
						
					}
				});
				
			}
			//else tell the local service to begin advertising
			else
			{
				//one session has been created, change the port, silly way
				mService.changePort();
				mService.startAdvertisement(name);
			}
		}

		@Override
		public void OnStart(String start, boolean value, boolean valueRun) {
			// TODO Auto-generated method stub
			
		}
    };
    
    
    //this is for service
    //as a callback to listen the service side, when the service finish the connection
    //it will call the method OnComplete()
	private XHListener mServiceListener = new XHListener()
    {
    	@Override
		public void OnComplete(Object value, int size) {
			state_S = State.CONNECTED_S;
			//if the local client has connected to the remote service,
			//launch the talk dialog
			if (State.CONNECTED_C == state_C)
			{
				//this runOnUiThread is used for running the UI code
				//without this, it will give the error:
				//only the original thread that created a view hierarchy can touch its views
				//be careful
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mVisibility = View.VISIBLE;
						disconnectButton.setVisibility(View.VISIBLE);
						talkButton.setVisibility(View.VISIBLE);
					}
				});
				
			}
			//else tell the local client to begin discovering
			else
			{
				//one session has been created, change the port, silly way
				mClient.changePort();
				
				//pass the well_name to the client to avoid the client join the session created by the local service
				mClient.setWellName(XHVariable.NAME_PREFIX + "." + name);
				mClient.startDiscover();
			}
		}

		@Override
		public void OnStart(String start, boolean value, boolean valueRun) {
			// TODO Auto-generated method stub
			
		}
    };
    
    //when in the talk dialog, the back button is pressed
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	  super.onActivityResult(requestCode, resultCode, data);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	this.menu = menu;
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch (item.getItemId())
    	{
	    	case R.id.quit:
	    	{
	    		finish();
	    		return true;
	    	}
	    	default:
	    		return super.onOptionsItemSelected(item);
    	}
    }
}